function EventBus () {
  // 存储事件总线状态
  this._bus = {}
}

EventBus.prototype = {
  on: function (evt, handler) {
    let bus = this._bus
    let handlers = bus[evt]
    if (Array.isArray(handlers)) {
      handlers.push(handler)
    } else {
      bus[evt] = [handler]
    }
    return function () {
      this.off(evt, handler)
    }.bind(this)
  },
  off: function (evt, handler) {
    let handlers = this._bus[evt]
    if (Array.isArray(handlers)) {
      if (handler) {
        for (let i = handlers.length - 1; i >= 0; i--) {
          if (handlers[i] === handler) {
            handlers.splice(i, 1)
            break
          }
        }
      } else {
        handlers.splice(0, handlers.length)
      }

      if (handlers.length === 0) {
        delete this._bus[evt]
      }
    }
  },
  fire: function (evt) {
    let handlers = this._bus[evt]
    if (Array.isArray(handlers)) {
      let args = Array.prototype.slice.call(arguments, 1)
      handlers.forEach(function (handler) {
        handler.apply(this, args)
      }.bind(this))
    }
  },
  fireWith: function (that, evt, ...args) {
    let handlers = this._bus[evt]
    if (Array.isArray(handlers)) {
      handlers.forEach(function (handler) {
        handler.apply(this, args)
      }.bind(that))
    }
  },
}

EventBus.prototype.constructor = EventBus

export default EventBus
